<template>
  <div class="app-container-table-border">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="0px"
      class="top-left">
<!--      <el-form-item label prop="reportName">-->
<!--        <el-input v-model="queryParams.reportName" placeholder="请输入试验名称" clearable @keyup.enter.native="handleQuery"-->
<!--          style="width: 180px;" />-->
<!--      </el-form-item>-->
      <el-form-item label prop="reportDate">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="～" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
<!--      <el-form-item label prop="ypCode">-->
<!--        <el-input v-model="queryParams.ypCode" placeholder="请输入样品编号" clearable @keyup.enter.native="handleQuery"-->
<!--          style="width: 180px;" />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb5 top-right-btn small-line-height">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['syrw:bsDataReport:export']">导出</el-button>
      </el-col>
    </el-row>
    <el-table class="report-table" border stripe v-loading="loading" :data="dataList"
      :header-cell-style="headerCellStyle" :span-method="objectSpanMethod" :max-height="tableHeight">
      <el-table-column label="序号" class-name="vertical-text" align="center" prop="xuh" width="40" />
      <el-table-column label="试验检测项目及参数" header-align="center" prop="name" min-width="80" show-overflow-tooltip />
      <el-table-column label="试验检测项目及参数" header-align="center" prop="title" min-width="80" show-overflow-tooltip />
      <el-table-column label="承包人" align="center">
        <el-table-column label="本月" align="center">
          <el-table-column label="组数" align="center" prop="chengbrzs" min-width="60" show-overflow-tooltip />
          <el-table-column label="合格率（%）" align="center" prop="chengbrhgl" min-width="60" show-overflow-tooltip />
        </el-table-column>
        <el-table-column label="开工累计" align="center" prop="chengbrkglj" min-width="60" show-overflow-tooltip />
      </el-table-column>
      <el-table-column label="监理人" align="center">
        <el-table-column label="本月" align="center">
          <el-table-column label="组数" class-name="span-warning" title-warning align="center" prop="jianlrzs" min-width="60"
            show-overflow-tooltip />
          <el-table-column label="合格率（%）" class-name="span-warning" align="center" prop="jianlrhgl" min-width="60"
            show-overflow-tooltip />
        </el-table-column>
        <el-table-column label="开工累计" class-name="span-warning" align="center" prop="jianlrkglj" min-width="60"
          show-overflow-tooltip />
        <el-table-column label="抽检频率（%）" class-name="span-warning" align="center" prop="choujpl" min-width="60"
          show-overflow-tooltip />
      </el-table-column>
      <el-table-column label="中心试验室" align="center">
        <el-table-column label="本月" align="center">
          <el-table-column label="组数" align="center" prop="zhongxsyszs" min-width="60" show-overflow-tooltip />
          <el-table-column label="合格率（%）" align="center" prop="zhongxsyshgl" min-width="60" show-overflow-tooltip />
        </el-table-column>
        <el-table-column label="开工累计" align="center" prop="zhongxsyskglj" min-width="60" show-overflow-tooltip />
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { getMonthlyReport } from "@/api/statistics";
export default {
  name: 'Syyb',
  data () {
    return {
      // 遮罩层
      loading: false,
      // 日期范围
      dateRange: [],
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        syType: undefined,
        deptId: undefined,
        reportName: undefined,
        reportDate: undefined,
        ypCode: undefined,
      },
      dataList: [],
      //合并表格
      columnArr: ["xuh", "name", 'title'],
      spanData: [],
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 170 + "px",
    };
  },
  // 监听顶部全局下拉
  computed: {
    visitedViews () {
      return this.$store.state.tagsView.visitedViews;
    },
    ...mapGetters(["deptId"])
  },
  watch: {
    deptId (newValue, oldValue) {
      this.queryParams.deptId = newValue;
      if (this.queryParams.syType) {
        this.getList();
      }
    }
  },
  created () {
    this.queryParams.deptId = this.$store.state.dept.deptId;
    this.getList();

  },
  mounted () {
  },
  methods: {
    /** 查询数据报告列表 */
    getList () {
      if (!this.queryParams.deptId) {
        this.$message.error("请先选择一个试验室");
        return;
      }
      this.loading = true;
      getMonthlyReport(this.addDateRange(this.queryParams, this.dateRange, 'ReportDate')).then((response) => {
        this.dataList = response.rows;
        this.loading = false;
        this.getSpanData(this.dataList);
        this.$forceUpdate();
      });
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.getList();
    },
    headerCellStyle ({ row, colunm, rowIndex, columnIndex }) {
      if (rowIndex === 0 && columnIndex == 2) {
        return { display: 'none' };
      }
      if (rowIndex == 0 && columnIndex == 1) {
        this.$nextTick(() => {
          document.querySelector(`.${row[columnIndex].id}`).setAttribute("colspan", "2");
        });
      }
    },
    // 计算需要合并的单元格
    getSpanData (data) {
      if (!data || data.length === 0 || !this.columnArr || this.columnArr.length === 0) {
        return;
      }
      this.spanData = [];
      for (let i = 0; i < this.columnArr.length; i++) {
        let contactDot = 0;
        const spanArr = [];
        data.forEach((item, index) => {
          // console.log(item)
          if (index === 0) {
            spanArr.push(1);
          } else {
            const isMergeRow = this.isMerge(data[index - 1], item, i);
            if (isMergeRow) {
              spanArr[contactDot] += 1;
              spanArr.push(0);
            } else {
              contactDot = index;
              spanArr.push(1);
            }
          }
        });
        this.spanData.push(spanArr);
      }

      // console.log(this.spanData)
    },
    // 是否合并
    isMerge (prevItem, item, index) {
      let ret = true;
      for (let i = 0; i <= index; i++) {
        const element = this.columnArr[i];
        if (item[element] !== prevItem[element]) {
          ret = false;
          break;
        }
      }
      return ret;
    },
    // 合并单元格
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (this.columnArr.includes(column.property)) {
        const index = this.columnArr.findIndex((item) => {
          return item == column.property;
        });
        if (this.spanData[index]) {

          if (this.spanData[index][rowIndex]) {
            const colspan = this.colspanManage({ row, column, rowIndex, columnIndex });
            return {
              rowspan: colspan == 0 ? 0 : this.spanData[index][rowIndex],
              colspan: colspan
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      }
    },
    // 处理横向合并
    colspanManage ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 1 || columnIndex == 2) {
        const info = this.dataList[rowIndex];
        if (info.name == info.title) {
          return columnIndex == 1 ? 2 : 0;
        } else {
          return 1;
        }
      } else {
        return 1;
      }
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "/monthlyReport/exportMonthlyReport",
        {
          ...this.queryParams
        },
        `bsDataReport_${new Date().getTime()}.xlsx`
      );
    }
  },
};
</script>
<style lang="scss" scoped>
::v-deep .report-table {
  .el-table__header-wrapper th {
    height: 22px !important;
  }
}

::v-deep td.span-warning {
  background-color: #f9f0d9 !important;
}

::v-deep .vertical-text {
  writing-mode: vertical-rl;
}
</style>
